﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaidou.Util;
using System.Data.SqlClient;
using System.Data;
using Kaidou.Model;
using System.Collections;

namespace Kaidou.Persister
{
    /**zhou-anyuan
     * シール受付明細のパーシスター
     *
     * @version $Revision: 1.13 $
     */
    public class TRN_Juchu_UketukePersister : Common
    {

        /**
         * データを挿入する
         *
         * @param con
         * @param model
         * @throws PersisterSQLException
         */
        public void insert(SqlDB con, TrnJuchud model)
        {
            LogManager.debug("TRN_Juchu_UketukePersister - TRN_Juchu_UketukePersister#insert in ---------------------------");
            try
            {
                String sql = "insert into trn_juchu_uketuke (juchu_no, juchu_rec_no, uketuke_st, reg_date) values(@juchu_no, @juchu_rec_no, @uketuke_st, @reg_date)";
                SqlParameter[] parmsU = new SqlParameter[] 
            {
                  new SqlParameter("@juchu_no", SqlDbType.VarChar,10), //
                  new SqlParameter("@juchu_rec_no", SqlDbType.Int,3),//
                  new SqlParameter("@uketuke_st", SqlDbType.VarChar,2), //
                  new SqlParameter("@reg_date", SqlDbType.DateTime) //
            };

                //try
                //{
                parmsU[0].Value = model.Id.JuchuNo;
                parmsU[1].Value = model.Id.JuchuRecNo;
                parmsU[2].Value = "10";
                parmsU[3].Value = System.DateTime.Now;

                int ret = con.ExecuteCmd(sql, parmsU);

                LogManager.debug("TRN_Juchu_UketukePersister -  成功！！！ ");
                //Logger.logWrite(TRN_Juchu_UketukePersister.class.getName(), "D", " 成功！！！ ");
                //}
                //finally
                //{
                //    con.Close();
                //}
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /**
         * 受付処理の完了したレコードを更新する
         *
         * @param con DB接続
         * @param model 受注明細データモデル
         * @param startDate 処理開始日時
         * @param endDate 処理終了日時
         * @throws PersisterSQLException
         */
        public void update(SqlDB con, TrnJuchud model, DateTime startDate, DateTime endDate)
        {
            try
            {
                String sql = "update trn_juchu_uketuke set uketuke_st='90', start_date=@start_date, end_date=@end_date where juchu_no=@juchu_no and juchu_rec_no=@juchu_rec_no";
                SqlParameter[] parmsU = new SqlParameter[]
            {
                  new SqlParameter("@start_date", SqlDbType.DateTime), //
                  new SqlParameter("@end_date", SqlDbType.DateTime),//
                  new SqlParameter("@juchu_no", SqlDbType.VarChar,10), //
                  new SqlParameter("@juchu_rec_no", SqlDbType.Int,3) //
            };
                //try
                //{
                parmsU[0].Value = startDate;
                parmsU[1].Value = endDate;
                parmsU[2].Value = model.Id.JuchuNo;
                parmsU[3].Value = model.Id.JuchuRecNo;

                int ret = con.ExecuteCmd(sql, parmsU);

                //}
                //finally
                //{
                //    con.Close();
                //}
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /**
         * 最後の AM 0:30 までの受付データのうち、未処理の受注明細レコード
         *
         * @param con
         * @return
         */
        public List<TrnJuchud> findReceiptOrderTarget(SqlDB con)
        {
            try
            {
                String sql =
                    "select d.juchu_no as juchu_no, d.juchu_rec_no as juchu_rec_no, d.seal_qty as seal_qty, d.trader_reg_no as trader_reg_no, d.seal_str_no as seal_str_no, d.seal_end_no as seal_end_no"
                        + " from trn_juchu_d d inner join trn_juchu_uketuke u"
                        + "   on d.juchu_no=u.juchu_no and d.juchu_rec_no=u.juchu_rec_no"
                        + " where u.uketuke_st='10' and u.reg_date <= @reg_date"
                        + " order by d.juchu_no, d.juchu_rec_no";
                SqlParameter[] parmsU = new SqlParameter[]
            {
                  new SqlParameter("@reg_date", SqlDbType.DateTime) //
                 
            };
                try
                {
                    List<TrnJuchud> result = new List<TrnJuchud>();
                    parmsU[0].Value = this.getTime0030();

                    SqlDataReader rdr = con.GetDataCmd(sql, parmsU);
                    if (rdr != null)
                    {
                        DataTable rs = DBUnit.ConvertDataReaderToDataTable(rdr);
                        foreach (DataRow row in rs.Rows)
                        {

                            TrnJuchud d = new TrnJuchud();
                            d.Id = new TrnJuchudId();
                            d.Id.JuchuNo = DBUnit.GetString(row["juchu_no"]);
                            d.Id.JuchuRecNo = (short)DBUnit.GetInt32(row["juchu_rec_no"]);
                            d.SealQty = DBUnit.GetInt32(row["seal_qty"]);
                            d.TraderRegNo = DBUnit.GetString(row["trader_reg_no"]);
                            d.SealStrNo = DBUnit.GetString(row["seal_str_no"]);
                            d.SealEndNo = DBUnit.GetString(row["seal_end_no"]);
                            result.Add(d);
                        }
                    }
                    return result;
                }
                finally
                {
                    //con.Close();
                }
            }
            catch (Exception e)
            {
                LogManager.debug("TRN_Juchu_UketukePersister -  findReceiptOrderTarget " + e.ToString());
                throw e;
            }
        }

        /**
         * 最後の AM 0:30 までの受付データのうち、未処理の受注明細レコード
         *
         * @return
         * @throws FrameworkException
         */
        public List<TrnJuchud> findReceiptOrderTarget()
        {
            try
            {
                SqlDB con = new SqlDB();
                try
                {
                    return findReceiptOrderTarget(con);
                }
                finally
                {
                    con.Close();
                }
            }
            catch (Exception e)
            {
                //LogManager.error("TRN_Juchu_UketukePersister -  findReceiptOrderTarget "+e.ToString());
                throw e;
            }
        }

        /**
         * 最後の AM 0:30 までの受付データが注文の受付処理を完了しているか
         *
         * @return
         * @throws FrameworkException
         */
        public bool isReceiptOrderTerminate()
        {
            bool result = false;
            try
            {
                //Connection con = Pool.getConnection();
                SqlDB con = new SqlDB();

                try
                {
                    String sql = "select count(*) as cnt from trn_juchu_uketuke where uketuke_st='10' and reg_date <= @reg_date";

                    SqlParameter[] parmsU = new SqlParameter[]
                    {
                          new SqlParameter("@reg_date", SqlDbType.DateTime) //
                         
                    };

                    try
                    {
                        parmsU[0].Value = this.getTime0030();

                        SqlDataReader rdr = con.GetDataCmd(sql, parmsU);

                        DataTable rs = DBUnit.ConvertDataReaderToDataTable(rdr);


                        if (DBUnit.GetInt32(rs.Rows[0]["cnt"]) == 0)
                        {
                            result = true;
                        }

                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                    finally
                    { }
                }
                finally
                {
                    //Pool.releaseConnection(con);
                    con.Close();
                }

            }
            catch (Exception e)
            {
                LogManager.debug("TRN_Juchu_UketukePersister - isReceiptOrderTerminate" + e.ToString());
                throw e;
            }

            return result;
        }

        /**
         * 本日の AM 00:30:00 を返す.
         * ただし、システム時刻が AM 00:30 以前のときは前日の AM 00:30:00 を返す
         *
         * @return
         */
        public System.DateTime getTime0030()
        {
            DateTime dnow = DateTime.Now;
            if (dnow.Hour == 0 && dnow.Minute < 30)
            {
                dnow.AddDays(-1);
            }
            dnow = new DateTime(dnow.Year, dnow.Month, dnow.Day, 0, 30, 0);

            return dnow;
        }

        /**
         * 指定された注文データの受付処理が終わったかどうか.
         * 終わっていれば true
         *
         * @param con
         * @param juchu_no
         * @return
         * @throws PersisterSQLException
         */
        public bool checkFinished(SqlDB con, String juchu_no)
        {
            String sql = "select count(*) as cnt from trn_juchu_uketuke where juchu_no=@juchu_no";
            try
            {

                SqlParameter[] parmsU = new SqlParameter[]
            {
                 new SqlParameter("@juchu_no", SqlDbType.VarChar,10) //
            };
                parmsU[0].Value = juchu_no;
                //try
                //{
                SqlDataReader rdr = con.GetDataCmd(sql, parmsU);
                DataTable rs = DBUnit.ConvertDataReaderToDataTable(rdr);


                if (DBUnit.GetInt32(rs.Rows[0]["cnt"]) > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
                //}
                //finally
                //{
                //    con.Close();
                //}
            }
            catch (Exception e)
            {
                LogManager.debug("TRN_Juchu_UketukePersister - checkFinished" + e.ToString());
                throw e;
            }
        }

        /**
         * 指定された保存期間を過ぎた処理済みデータを削除する
         *
         * @param keepTerm 受付データの保存期間
         * @throws PersisterSQLException
         */
        public void deleteBeforeBorder(SqlDB con, int keepTerm)
        {

            DateTime dnow = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);

            dnow.AddDays(-keepTerm);


            String sql = "delete from trn_juchu_uketuke where uketuke_st='90' and reg_date < @reg_date";
            try
            {
                SqlParameter[] parmsU = new SqlParameter[]
            {
                  new SqlParameter("@reg_date", SqlDbType.DateTime) //
                 
            };
                parmsU[0].Value = dnow;

                //try
                //{
                int ret = con.ExecuteCmd(sql, parmsU);
                //}
                //finally
                //{
                //    con.Close();
                //}
            }
            catch (Exception e)
            {
                LogManager.debug("TRN_Juchu_UketukePersister - deleteBeforeBorder" + e.ToString());
                throw e;
            }
        }
    }
}
